/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.module.home

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory
import com.tencent.tencentmap.mapsdk.maps.TencentMap
import com.tencent.tencentmap.mapsdk.maps.model.*
import kotlinx.android.synthetic.main.fragment_nearby.*
import org.greenrobot.eventbus.EventBus
import top.stime21.myneighbours.Events
import top.stime21.myneighbours.R
import top.stime21.myneighbours.base.BuzMvpFragment
import top.stime21.myneighbours.data.entity.Need
import top.stime21.myneighbours.module.login.NeedContract
import top.stime21.myneighbours.module.login.presenter.NeedPrensenterImpl


/**
 * Author: czmc  Email: zxc6355533@163.com
 * Version:	1.0  Date:2018/3/1
 */

class NearByFragment : BuzMvpFragment<NeedContract.Presenter>(),NeedContract.View{
    override fun onDetailsGetSuccess(data: Need?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onFinishSuccess() {
    }

    override fun onMyNeedMoreGetSuccess(data: List<Need>?) {
    }

    override fun onMyNeedGetSuccess(data: List<Need>?) {
    }

    override fun onPublishSuccess() {
    }

    override fun onAcceptSuccess() {
    }

    override fun onCancleSuccess() {

    }

    override fun onNearbySuccess(data: List<Need>?) {
        drawMarks(data!!)
        (recycleView.adapter as NeedAdapter).setUpdateData(data)
    }

    private fun drawMarks(data: List<Need>) {
        if(mapview!=null){
            for( n in data){
                mapview.map.addMarker(MarkerOptions().position(LatLng(n.latitude, n.longitude)).icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_need)))
            }
        }
    }

    override fun onSearchSuccess(data: List<Need>?) {
    }

    override fun getPresenter(): NeedContract.Presenter {
        return NeedPrensenterImpl(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_nearby
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val locationManager = TencentLocationManager.getInstance(this.activity)
        val tencentLocationRequest = TencentLocationRequest.create().setInterval(100000L)
        val error = locationManager.requestLocationUpdates(tencentLocationRequest,listener )
        btn_location.setOnClickListener(View.OnClickListener {
            val tencentLocationRequest = TencentLocationRequest.create().setInterval(100000L)
            val error = locationManager.requestLocationUpdates(tencentLocationRequest,listener )
        })
        mapview.map.setOnMarkerClickListener {
            marker ->
            if(mylocationmark != marker && recycleView.adapter!=null && recycleView.adapter.itemCount>0){
                view_list.visibility = View.VISIBLE
            }
            true
        }
        mapview.map.setOnCameraChangeListener(cameralistener)
        recycleView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL,false)
        recycleView.adapter = NeedAdapter(context!!)
    }

    private val cameralistener : TencentMap.OnCameraChangeListener? =object :TencentMap.OnCameraChangeListener{
        override fun onCameraChangeFinished(p0: CameraPosition?) {
        }

        override fun onCameraChange(p0: CameraPosition?) {
            view_list.visibility = View.GONE
        }

    }

    private var mylocationmark: Marker? = null;
    private val listener = object : TencentLocationListener {
        override fun onStatusUpdate(name: String?, status: Int, desc: String?) {
        }
        override fun onLocationChanged(location: TencentLocation?, error: Int, reason: String?) {
            Log.i("tc_location","${location.toString()}")
            val latLng = LatLng(location!!.getLatitude(), location!!.getLongitude())
            mapview.map.animateCamera(CameraUpdateFactory.newLatLng(latLng))
            if(mylocationmark!=null) {
                mylocationmark!!.remove()
            }
            mylocationmark = mapview.map.addMarker(MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location)))
            EventBus.getDefault().post(Events.CityNotify(location.address))
            mPrensenter!!.nearby(location.latitude,location.longitude)
            TencentLocationManager.getInstance(activity).removeUpdates(this)
        }
    }
    override fun onDestroy() {
        if (mapview != null)
            mapview.onDestroy()
        super.onDestroy()
    }

    override fun onPause() {
        if (mapview != null)
            mapview.onPause()
        super.onPause()
    }

    override fun onResume() {
        if (mapview != null)
            mapview.onResume()
        super.onResume()
    }

    override fun onStop() {
        if (mapview != null)
            mapview.onStop()
        super.onStop()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if(isVisibleToUser && rootView!=null){
            view_list.visibility = View.GONE
        }
    }

}